package com.pay.wap;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

import com.wap.pay.activity.PayWebViewActivity;
import com.wap.pay.interfaces.NetworkCallback;
import com.wap.pay.model.WapPayInfo;
import com.wap.pay.view.PayWebView;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class MainActivity extends Activity implements View.OnClickListener {
    private static final String PAY_INFO = "获取支付信息...";
    private String BASE_URL = "http://xwhzpp666.tpddns.cn:9001/form/pay?";
    private String PAYTYPE = "3"; // 支付方式
    private String CUSTOM_NAME = "name"; // 客户名称
    private String CUSTOM_IP = "ip"; // 客户ip
    private static final String TERMINAL = "3"; // 终端设备固定值 ANDROID 3 IOS 2
    private static final String ISWAPPAY = "5"; // 支付场景固定值5
    private EditText editPrice;
    private EditText editCode;
    private EditText editComKey;
    private EditText editReturnUrl;
    private EditText editNoticeUrl;

    String[][] OPTION_PARAM = {{"p8_signtype", ""}, {"p10_paychannelnum", ""}, {"p11_cardtype", ""},
            {"p12_channel", ""}, {"p13_orderfailertime", ""}, {"p15_customcontacttype", ""},
            {"p16_customcontact", ""}, {"p18_product", ""}, {"p19_productcat", ""},
            {"p20_productnum", ""}, {"p21_pdesc", ""}, {"p22_version", ""},
            {"p23_charset", ""}, {"p24_remark", ""}};
    private ProgressDialog mProgressDialog;

    private PayWebView mPayWebView;

    /**
     * simulate user ,get url
     * the url url for user, and then call our sdk to pay
     *
     * @param code       商户号
     * @param p7_sign    商户传递参数签名
     * @param money      支付金额
     * @param returnUrl  用户跳转地址,用于显示支付结果
     * @param noticeUrl  支付结果通知
     * @param baseUrl    用户BASE_URL
     * @param payType    支付方式
     * @param order      订单 
     * @param orderTime  订单时间
     * @param customName 商户名
     * @param customIp   商户ip
     * @param terminal   终端设备固定值
     * @param iswappay   支付场景固定值
     * @return url
     */
    private WapPayInfo getWebPayInfo(String money, String code, String p7_sign, String returnUrl,
                                     String noticeUrl, String baseUrl, String payType,
                                     String order, String orderTime, String customName,
                                     String customIp, String terminal, String iswappay) {
        WapPayInfo wapPayInfo = new WapPayInfo();
        wapPayInfo.setMoney(money);
        wapPayInfo.setCode(code);
        wapPayInfo.setP7_sign(p7_sign);
        wapPayInfo.setReturnUrl(returnUrl);
        wapPayInfo.setNoticeUrl(noticeUrl);
        wapPayInfo.setBaseUrl(baseUrl);
        wapPayInfo.setPayType(payType);
        wapPayInfo.setOrderTime(orderTime);
        wapPayInfo.setOrder(order);
        wapPayInfo.setCustomName(customName);
        wapPayInfo.setCustomIp(customIp);
        wapPayInfo.setTerminal(terminal);
        wapPayInfo.setIswappay(iswappay);
        /**下列可选*/
        Map<String, String> optionalMap = new HashMap<>();
        for (String[] param : OPTION_PARAM) {
            if (!TextUtils.isEmpty(param[1])) {
                optionalMap.put(param[0], param[1]);
            }
        }
        wapPayInfo.setOptionalMap(optionalMap);
        return wapPayInfo;
    }

    /**
     * 强烈建议p7_sign 数据签名过程在服务器端完成,
     * 非常不推荐商户支付密钥存放在客户端
     * demo由于展示原因,在手机端进行
     **/
    private String getSignData(String code, String order, String money, String returnUrl,
                               String noticeUrl, String orderTime, String comKey) {
        String p7_sign = PayMD5Util.getMD5(code + "&" + order + "&" + money +
                "&" + returnUrl + "&" + noticeUrl + "&" + orderTime + comKey).toUpperCase();
        return p7_sign;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        editPrice = (EditText) findViewById(R.id.edit_price);
        editCode = (EditText) findViewById(R.id.edit_code);
        editComKey = (EditText) findViewById(R.id.edit_com_key);
        editReturnUrl = (EditText) findViewById(R.id.edit_return_url);
        editNoticeUrl = (EditText) findViewById(R.id.edit_notice_url);
        Spinner shopSpinner = (Spinner) findViewById(R.id.shop_spinner);
        Spinner payModelSpinner = (Spinner) findViewById(R.id.pay_model_spinner);

        Button btn_submit_webview = (Button) findViewById(R.id.btn_submit_webview);
        Button btn_submit_browser = (Button) findViewById(R.id.btn_submit_browser);
        btn_submit_webview.setOnClickListener(this);
        btn_submit_browser.setOnClickListener(this);
        mPayWebView = new PayWebView(this);
        shopSpinner.setSelection(0);
        payModelSpinner.setSelection(0);

        shopSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                try {
                    String domainName = getResources().getStringArray(R.array.shop_domain_name)[position];
                    BASE_URL = domainName + "/form/pay?";
                    editCode.setText(getResources().getStringArray(R.array.shop_code)[position]);
                    editComKey.setText(getResources().getStringArray(R.array.shop_comkey)[position]);
                    editReturnUrl.setText(String.format("%s/Form/TestReturn", domainName));
                    editNoticeUrl.setText(String.format("%s/Form/TestNotice", domainName));
                } catch (Resources.NotFoundException e) {
                    e.printStackTrace();
                    Log.e("cus", "数组数据转换错误");
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        payModelSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    PAYTYPE = "3";
                } else {
                    PAYTYPE = "4";
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        dismissProgressDialog();
    }


    private void showProgressDialog() {
        if (null == mProgressDialog) {
            mProgressDialog = ProgressDialog.show(MainActivity.this, "", "", false, true, null);
        }
        mProgressDialog.setMessage(PAY_INFO);
        mProgressDialog.show();
    }

    private void dismissProgressDialog() {
        if (null != mProgressDialog) {
            mProgressDialog.dismiss();
        }
    }

    public void onClick(View view) {
        @SuppressLint("SimpleDateFormat")
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date();
        String code = editCode.getText().toString().trim();
        String price = editPrice.getText().toString().trim();
        String returnurl = editReturnUrl.getText().toString().trim();
        String noticeurl = editNoticeUrl.getText().toString().trim();
        String comkey = editComKey.getText().toString().trim();
        /**TODO 再次说明,非常不推荐签名过程在移动端完成,强烈建议在服务器端完成**/
        String p7_sign = getSignData(code, String.format("TestOrder_%s", dateFormat.format(date)),
                price, returnurl, noticeurl, dateFormat.format(date), comkey);

        switch (view.getId()) {
            case R.id.btn_submit_webview:
                WapPayInfo wapPayInfo = getWebPayInfo(
                        price, code, p7_sign, returnurl, noticeurl, BASE_URL, PAYTYPE,
                        String.format("TestOrder_%s", dateFormat.format(date)),
                        dateFormat.format(date), CUSTOM_NAME, CUSTOM_IP, TERMINAL, ISWAPPAY);
                Log.d("junfutong", "wapPayInfo = " + wapPayInfo.toString());
                PayWebViewActivity.startActivity(wapPayInfo, MainActivity.this);
                break;
            case R.id.btn_submit_browser:
                wapPayInfo = getWebPayInfo(
                        price, code, p7_sign, returnurl, noticeurl, BASE_URL, PAYTYPE,
                        String.format("TestOrder_%s", dateFormat.format(date)),
                        dateFormat.format(date), CUSTOM_NAME, CUSTOM_IP, TERMINAL, ISWAPPAY);
                Log.d("junfutong", "wapPayInfo = " + wapPayInfo.toString());
                mPayWebView.loadUrl(new NetworkCallback() {
                    @Override
                    public void onResult(boolean success) {
                        if (success) {
                            dismissProgressDialog();
                        } else {
                            showProgressDialog();
                        }
                    }
                }, wapPayInfo);
                break;
        }
    }
}
